package com.wyz.demo.core.infrastructure.utils;

import java.io.File;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author: wei yz
 * @Date: 2022/7/9 16:15
 */
public class PackageUtil {

    public static void main(String[] args) {
        String packageName = "com.wyz.calibur.infrastructure.db";
//        Set<String> sets = getPackageChild(packageName, "com");
//        for (String set : sets) {
//            System.out.println("--->" + set);
//        }
        String[] sets = getDbPaks(packageName, "com");
        for (String set : sets) {
            System.out.println("--->" + set);
        }
    }

    private static String[] getDbPaks(String path, String lastIndexStr) {
        Set<String> sets = getPackageChild(path, lastIndexStr);
        return sets.stream().toArray(String[]::new);
    }

    /**
     * 获取指定包下所有子包
     */
    public static Set<String> getPackageChild(String packageName, String lastIndexStr) {
        // 获取当前位置
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        // 转化路径，Linux 系统
        String packagePath = packageName.replace(".", "/");
        // 具体路径
        URL url = loader.getResource(packagePath);
        String fileUrl = url.getFile();
        File file = new File(fileUrl);
        fileUrl = file.getPath();
        Set<String> filePathList = new HashSet<String>();
        return getFileChildPath(fileUrl, filePathList, lastIndexStr);
    }

    /**
     * 获取指定文件夹下的子包
     */
    public static Set<String> getFileChildPath(String filePath, Set<String> filePathList, String lastIndexStr) {
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files.length > 0) {
                for (File file1 : files) {
                    if (!file1.isDirectory()) {
                        filePath = filePath.substring(filePath.lastIndexOf(lastIndexStr)).replace("\\", ".");
                        filePathList.add(filePath);
                    }
                    getFileChildPath(file1.getPath(), filePathList, lastIndexStr);
                }
            }
        }

        return filePathList;
    }
}
